package jn.example.apt;

import com.google.auto.service.AutoService;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Resource;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import jn.example.apt.annotation.GetterAndSetter;
import org.objectweb.asm.ClassReader;

@AutoService(Processor.class)
public class GetterAndSetterProcessor extends AbstractProcessor {

  @Override
  public Set<String> getSupportedAnnotationTypes() {
    Set<String> supportedTypes = new HashSet<>();
    supportedTypes.add(Resource.class.getCanonicalName());
    supportedTypes.add(GetterAndSetter.class.getCanonicalName());
    return supportedTypes;
  }

  @Override
  public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latestSupported();
  }

  @Override
  public synchronized void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);
  }

  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    System.out.println("Processing GETTER and SETTER");
    for (Element element : roundEnv.getElementsAnnotatedWith(GetterAndSetter.class)) {
      try {
        TypeElement typeElement = (TypeElement) element;
        System.out.println("APT run start typeElement..." + typeElement);

        String currentClassName = typeElement.getSimpleName().toString();
        String currentPackageName = processingEnv.getElementUtils().getPackageOf(typeElement).toString();

        String className = currentClassName + "Generated";
        String content = generateGeneratedClassContent(currentPackageName, className);

        try {
          // 创建一个新的Java源文件
          Writer writer = processingEnv.getFiler().createSourceFile(currentPackageName + "." + className, typeElement)
              .openWriter();
          writer.write(content);
          writer.flush();
          writer.close();
        }
        catch (IOException e) {
          e.printStackTrace();
        }

        ClassReader reader = new ClassReader(processingEnv.getElementUtils().getBinaryName(typeElement).toString());

//                InputStream inputStream = new FileInputStream(element.getEnclosingElement().toString().replace('.', '/') + ".class");
//                ClassReader reader = new ClassReader(inputStream);
//
//                ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
//                ClassVisitor visitor = new GenerateSetterGetterClassVisitor(writer);
//                reader.accept(visitor, 0);
//
//                // 获取修改后的字节码并写回文件
//                byte[] modifiedClassBytes = writer.toByteArray();
//                FileOutputStream outputStream = new FileOutputStream(element.getEnclosingElement().toString().replace('.', '/') + ".class");
//                outputStream.write(modifiedClassBytes);
//                outputStream.close();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
    return true;
  }

  private String generateGeneratedClassContent(String packageName, String className) {
    return "package " + packageName + ";\n\npublic class " + className
        + " {\n\n    public static void printMessage() {\n        System.out.println(\"Hello from " + className
        + "!\");\n    }\n\n}\n";
  }
}
